package fractal;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import jinyilw.common.SettingTools;

public class ColorMap implements Cloneable
{
	private final static int dataLength = 20;
	private int[] key = new int[dataLength];
	private int[] value = new int[dataLength];
	public int length = 0;

	@Override
	public ColorMap clone()
	{
		try
		{
			ColorMap colorMap = (ColorMap) super.clone();
			colorMap.key = key.clone();
			colorMap.value = value.clone();
			return colorMap;
		} catch (CloneNotSupportedException e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public void add(int k, int v)
	{
		if (length == 0)
		{
			key[0] = k;
			value[0] = v;
			length++;
		} else
		{
			int i = 0;
			for (; i < length; i++)
				if (key[i] == k)
				{
					value[i] = v;
					return;
				}

			if (i < dataLength)
			{
				key[i] = k;
				value[i] = v;
				length++;
			}
		}

	}

	public boolean remove(int k)
	{
		for (int i = 0; i < length; i++)
		{
			if (key[i] == k)
			{
				for (int j = i; j < length - 1; j++)
				{
					key[j] = key[j + 1];
					value[j] = value[j + 1];
				}
				length--;
				return true;
			}
		}
		return false;
	}

	public void clear()
	{
		length = 0;
	}

	public boolean isContain(int k)
	{
		for (int i = 0; i < length; i++)
			if (key[i] == k)
				return true;
		return false;
	}

	public int length()
	{
		return length;
	}

	public int getKey(int index)
	{
		return key[index];
	}

	public int getValue(int index)
	{
		return value[index];
	}

	public void writeToDataStream(DataOutputStream dos) throws IOException
	{
		dos.writeInt(length);
		for (int i = 0; i < length; i++)
		{
			dos.writeInt(key[i]);
			dos.writeInt(value[i]);
		}
	}

	public void readFromDataStream(DataInputStream dis) throws IOException
	{
		length = dis.readInt();
		for (int i = 0; i < length; i++)
		{
			key[i] = dis.readInt();
			value[i] = dis.readInt();
		}
	}

	public void putCustomData()
	{
		SettingTools.putDefaultSettingData("length", length);
		for (int i = 0; i < length; i++)
		{
			SettingTools.putDefaultSettingData("key" + i, key[i]);
			SettingTools.putDefaultSettingData("value" + i, value[i]);
		}
	}

	public void getCustomData()
	{
		length = (Integer) SettingTools.getDefaultSettingData("length", length);
		for (int i = 0; i < length; i++)
		{
			key[i] = (Integer) SettingTools.getDefaultSettingData("key" + i,
					key[i]);
			value[i] = (Integer) SettingTools.getDefaultSettingData("value" + i,
					value[i]);
		}
	}
}
